#include "DiagramScene.h"
#include "AbstractManager.h"
#include "AbstractMappingWindow.h"
#include "NodeItem.h"
#include "LineItem.h"
#include "AbstractPanel.h"
#include <QKeyEvent>
#include <QPainter>
#include <vector>
#include <cassert>

DiagramScene::DiagramScene(AbstractManager* manager)
{
	this->_manager = manager;
}

DiagramScene::~DiagramScene(void)
{
}

void DiagramScene::mousePressEvent( QGraphicsSceneMouseEvent* mouseEvent)
{
	QGraphicsScene::mousePressEvent(mouseEvent);
}

void DiagramScene::mouseReleaseEvent( QGraphicsSceneMouseEvent* mouseEvent)
{
	QGraphicsScene::mouseReleaseEvent(mouseEvent);
}

void DiagramScene::mouseMoveEvent( QGraphicsSceneMouseEvent* mouseEvent)
{
	QGraphicsScene::mouseMoveEvent(mouseEvent);
}

void DiagramScene::keyPressEvent ( QKeyEvent * keyEvent ){
	
	if ( keyEvent->matches(QKeySequence::Delete)){

		while ( !selectedItems().isEmpty()){
			int i = selectedItems().size() - 1;
			Item* deleteItem = dynamic_cast<Item*>(this->selectedItems().at(i));
			assert(deleteItem);
			deleteItem->remove();
			_manager->getMappingDialog()->cleanTreeWidget();
		}

	}

	QGraphicsScene::keyPressEvent(keyEvent);
}

AbstractManager* DiagramScene::getManager()
{
	return this->_manager;
}

void DiagramScene::setSceneRect( qreal x, qreal y, qreal w, qreal h )
{
	QGraphicsScene::setSceneRect(x,y,w,h);
}

WOP_Entry* DiagramScene::getEntry()
{
	return this->_currentEntry;
}

void DiagramScene::setEntry( WOP_Entry* entry )
{
	this->_currentEntry = entry;
}

void DiagramScene::addItem( AbstractShapeItem * item)
{
	QGraphicsScene::addItem(item);

	if ( item->nodeType() == AbstractShapeItem::MAPPING_NODE ) {
		this->clearSelection();
		item->setSelected(true);
	}

}

void DiagramScene::addItem( LineItem * line )
{
	QGraphicsScene::addItem(line);
	this->clearSelection();
	line->setSelected(true);
}

void DiagramScene::addItem( QGraphicsItem * item )
{
	QGraphicsScene::addItem(item);
}

void DiagramScene::addInputPaneltoCanvas()
{
	AbstractPanel *panel = _manager->createInputPanel();
	this->addItem(panel);
	panel->setPos(0,0);
}

void DiagramScene::addOutputPanelToCanvas() {
	AbstractPanel * panel = this->_manager->createOutputPanel();
	this->addItem( panel );
	panel->setPos( this->sceneRect().width() - 153, 0 );
}
